package com.controller;

import com.annotations.RequestMappping;
import com.pojo.TbAddress;
import com.pojo.TbUser;
import com.service.AddressService;
import com.service.impl.AddressServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
@RequestMappping("/address")
public class AddressController {

    private AddressService addressService = new AddressServiceImpl();

    //添加地址
    @RequestMappping("/create")
    public String createAddress(HttpServletRequest req, HttpServletResponse resp) {
        TbAddress tbAddress = new TbAddress();
        TbUser loginUser = (TbUser) req.getSession().getAttribute("loginUser");
        tbAddress.setUid(loginUser.getId());
        Map<String, String[]> map = req.getParameterMap();
        try {
            BeanUtils.populate(tbAddress, map);
            addressService.createAddress(tbAddress);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/index.jsp";
    }

    @RequestMappping("/show")
    public String show(HttpServletRequest req, HttpServletResponse resp) {
        TbUser loginUser = (TbUser) req.getSession().getAttribute("loginUser");
        Long id = loginUser.getId();
        List<TbAddress> list = addressService.showAddress(id);
        req.getSession().setAttribute("list", list);
        return "redirect:/self_info.jsp";
    }
    @RequestMappping("/add")
    public String preUpdate(HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("id");
        int aid = Integer.parseInt(id);
        TbAddress address = addressService.selAddress(aid);
        req.setAttribute("add", address);
        return "forward:/self_info.jsp";


    }

    @RequestMappping("/update")
    public String update(HttpServletRequest req, HttpServletResponse resp) {
        TbAddress tbAddress = new TbAddress();
        Map<String, String[]> map = req.getParameterMap();
        try {
            BeanUtils.populate(tbAddress, map);
            addressService.update(tbAddress);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/self_info.jsp";

    }
    @RequestMappping("/del")
    public String del(HttpServletRequest req, HttpServletResponse resp){
        String id = req.getParameter("id");
        int aid = Integer.parseInt(id);
        addressService.delAdd(aid);
        return "redirect:/self_info.jsp";
    }
}
